package com.santoker.user.service.service.biz.record.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.santoker.baseservice.ApiResponseBody;
import com.santoker.baseservice.ApiResponseCode;
import com.santoker.baseservice.enums.IsDeleteEnum;
import com.santoker.baseservice.util.DateUtils;
import com.santoker.baseservice.util.Generator;
import com.santoker.user.service.dto.vo.DelBodyVo;
import com.santoker.user.service.dto.vo.DelListBodyVo;
import com.santoker.user.service.dto.vo.record.*;
import com.santoker.user.service.dto.vo.share.RoastDataVo;
import com.santoker.user.service.dto.vo.share.RoastEvent;
import com.santoker.user.service.dto.vo.share.SharedDataVo;
import com.santoker.user.service.exception.CommonServiceException;
import com.santoker.user.service.model.User;
import com.santoker.user.service.model.UserRecord;
import com.santoker.user.service.model.UserRecordDetail;
import com.santoker.user.service.service.biz.record.RecordService;
import com.santoker.user.service.service.common.IUserRecordDetailService;
import com.santoker.user.service.service.common.IUserRecordService;
import com.santoker.user.service.service.common.IUserService;
import com.santoker.user.service.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class RecordServiceImpl implements RecordService {

    @Autowired
    private IUserRecordService iUserRecordService;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private IUserRecordDetailService iUserRecordDetailService;

    @Override
    public List<UserRecordVo> getUserRecordList(Integer userId) {

        log.info("------------------------------ 单个用户记录列表  ------------------------------");
        ApiResponseBody.printRequestParam(userId);

        // 查询用户记录列表
        List<UserRecord> userRecordList = iUserRecordService.findListByUserId(userId);
        return getUserRecordListVos(userRecordList);
    }

    @Override
    public List<UserRecordVo> getUserShareList(Integer userId) {

        log.info("------------------------------ 单个用户分享列表  ------------------------------");
        ApiResponseBody.printRequestParam(userId);

        // 查询用户记录列表
        List<UserRecord> userRecordList = iUserRecordService.findShareListByUserId(userId);
        return getUserRecordListVos(userRecordList);
    }

    private List<UserRecordVo> getUserRecordListVos(List<UserRecord> userRecordList) {
        List<UserRecordVo> dataList = userRecordList.stream().map(item -> {
            UserRecordVo data = UserRecordVo.builder()
                    .recordId(item.getId())
                    .userId(item.getUserId())
                    .userName(iUserService.getNickNameByUserId(item.getUserId()))
                    .weight(item.getWeight())
                    .title(item.getTitle())
                    .type(item.getType())
                    .share(item.getShare())
                    .selected(item.getSelected())
                    .train(item.getTrain())
                    .isTop(item.getIsTop())
                    .createTime(item.getCreatedAt())
                    .build();
            return data;
        }).collect(Collectors.toList());
        return dataList;
    }

    @Override
    public SharedDataVo getSharedData(Integer recordId) {

//        log.info("------------------------------ 单个分享记录  ------------------------------");
//        ApiResponseBody.printRequestParam(recordId);

        // 验证用户记录是否存在
        UserRecord userRecord = iUserRecordService.getById(recordId);
        if (Objects.isNull(userRecord)) {
            throw new CommonServiceException(ApiResponseCode.USER_RECORD_NOT_EXIST);
        }

        // 曲线详情信息
        RoastDataVo roastDataVo = new RoastDataVo();

        // 查询用户记录详情列表
        List<UserRecordDetail> userRecordDetailList = iUserRecordDetailService.getUserRecordDetailList(userRecord.getId());
        if (CollectionUtils.isNotEmpty(userRecordDetailList)) {
            int size = userRecordDetailList.size();
            ArrayList<Integer> tArray = new ArrayList<>(size); // 时间
            ArrayList<Float> btArray = new ArrayList<>(size); // 豆温
            ArrayList<Float> etArray = new ArrayList<>(size); // 风温
            ArrayList<Integer> fpArray = new ArrayList<>(size); // 火力大小
            ArrayList<Integer> dpArray = new ArrayList<>(size); // 风门大小
            ArrayList<Integer> msArray = new ArrayList<>(size); // 搅拌机转速大小
            ArrayList<RoastEvent> eventArray = new ArrayList<>(); // 操作记录
            for (UserRecordDetail item : userRecordDetailList) {
                tArray.add(Integer.valueOf(item.getTNode()));
                btArray.add(Float.valueOf(item.getBtNode()));
                etArray.add(Float.valueOf(item.getEtNode()));
                fpArray.add(Integer.valueOf(item.getFpNode()));
                dpArray.add(Integer.valueOf(item.getDpNode()));
                msArray.add(Integer.valueOf(item.getMsNode()));
                if (item.getEvNode() > 0) {
                    RoastEvent roastEvent = RoastEvent.builder()
                            .time(Integer.valueOf(item.getTNode()))
                            .bt(Float.valueOf(item.getBtNode()))
                            .event(item.getEvNode())
                            .build();
                    eventArray.add(roastEvent);
                }
            }
            roastDataVo.setTimeArray(tArray);
            roastDataVo.setBeanTemperatureArray(btArray);
            roastDataVo.setEnvironmentTemperatureArray(etArray);
            roastDataVo.setFirepowerArray(fpArray);
            roastDataVo.setDamperArray(dpArray);
            roastDataVo.setMotorSpeedArray(msArray);
            roastDataVo.setEventArray(eventArray);
        }

        SharedDataVo sharedDataVo = SharedDataVo.builder()
                .recordId(userRecord.getId())
                .title(userRecord.getTitle())
                .data(roastDataVo)
                .build();
        return sharedDataVo;
    }

    @Override
    public List<UserVo> getUserListShareAndSelect() {

        log.info("------------------------------ 分享、精选用户列表  ------------------------------");

        // 查询用户分享、精选曲线列表
        List<UserRecord> userRecordList = iUserRecordService.findGroupByUserIdShareAndSelect();
        return getUserVoList(userRecordList);
    }

    @Override
    public List<UserVo> getUserListSelect() {

        log.info("------------------------------ 精选用户列表  ------------------------------");

        // 查询用户精选曲线列表
        List<UserRecord> userRecordList = iUserRecordService.findGroupByUserIdSelect();
        return getUserVoList(userRecordList);
    }

    @Override
    public List<UserVo> getAllUser() {

        log.info("------------------------------ 用户列表  ------------------------------");

        // 查询所有用户信息
        List<User> userList = iUserService.findAll();
        return userList.stream().map(item -> {
            UserVo userVo = UserVo.builder()
                    .userId(item.getId())
                    .userName(item.getNickname())
                    .mobile(item.getMobile())
                    .email(item.getEmail())
                    .openid(item.getOpenid())
                    .uploadRecordNum(iUserRecordService.getTotalByUserId(item.getId()))
                    .locked(item.getLocked())
                    .createTime(item.getCreatedAt())
                    .build();
            return userVo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<UserVo> searchUserByName(String userName) {

        log.info("------------------------------ 姓名搜索用户  ------------------------------");
        ApiResponseBody.printRequestParam(userName);

        // 根据姓名，查询用户列表
        List<User> userList = iUserService.findByNickNameLike(userName);
        return userList.stream().map(item -> {
            UserVo userVo = UserVo.builder()
                    .userId(item.getId())
                    .userName(item.getNickname())
                    .mobile(item.getMobile())
                    .email(item.getEmail())
                    .openid(item.getOpenid())
                    .uploadRecordNum(iUserRecordService.getTotalByUserId(item.getId()))
                    .locked(item.getLocked())
                    .createTime(item.getCreatedAt())
                    .build();
            return userVo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<UserVo> searchUserByMobile(String mobile) {

        log.info("------------------------------ 手机号搜索用户  ------------------------------");
        ApiResponseBody.printRequestParam(mobile);

        // 根据手机号，查询用户列表
        List<User> userList = iUserService.findByMobileLike(mobile);
        return userList.stream().map(item -> {
            UserVo userVo = UserVo.builder()
                    .userId(item.getId())
                    .userName(item.getNickname())
                    .mobile(item.getMobile())
                    .email(item.getEmail())
                    .openid(item.getOpenid())
                    .uploadRecordNum(iUserRecordService.getTotalByUserId(item.getId()))
                    .locked(item.getLocked())
                    .createTime(item.getCreatedAt())
                    .build();
            return userVo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<UserRecordVo> getUserRecordListByTitle(String title, Integer searchType) {

        log.info("------------------------------ 搜索曲线  ------------------------------");
        ApiResponseBody.printRequestParam(title, searchType);

        List<UserRecord> userRecordList = null;

        // 非分享记录列表
        if (searchType == 0) {
            userRecordList = iUserRecordService.findByTitleLikeAndShare(title, 0);
        }
        // 分享记录列表
        else if (searchType == 1) {
            userRecordList = iUserRecordService.findByTitleLikeAndShare(title, 1);
        }
        // 分享 & 精选记录列表
        else {
            userRecordList = iUserRecordService.findByTitleLikeAndShareAndSelected(title, 1, 1);
        }
        return getUserRecordVos(userRecordList);
    }

    @Override
    public List<UserRecordVo> getAllRecord() {

        log.info("------------------------------ 所有曲线  ------------------------------");

        // 查询所有记录列表
        List<UserRecord> userRecordList = iUserRecordService.findByAll();
        return getUserRecordVos(userRecordList);
    }

    private List<UserRecordVo> getUserRecordVos(List<UserRecord> userRecordList) {
        return userRecordList.stream().map(item -> {
            UserRecordVo userRecordVo = UserRecordVo.builder()
                    .recordId(item.getId())
                    .userId(item.getUserId())
                    .userName(iUserService.getNickNameByUserId(item.getUserId()))
                    .title(item.getTitle())
                    .type(item.getType())
                    .share(item.getShare())
                    .selected(item.getSelected())
                    .weight(item.getWeight())
                    .train(item.getTrain())
                    .isTop(item.getIsTop())
                    .createTime(item.getCreatedAt())
                    .build();
            return userRecordVo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<UserRecordVo> getAllTrainRecord(String type) {

        log.info("------------------------------ 所有训练集曲线  ------------------------------");
        ApiResponseBody.printRequestParam(type);

        // 查询所有训练集记录列表
        List<UserRecord> userRecordList = iUserRecordService.findByTrainAndType(1, type);
        return getUserRecordVos(userRecordList);
    }

    @Override
    public List<UserVo> getUserListShare() {

        log.info("------------------------------ 分享用户列表  ------------------------------");

        // 查询用户精选曲线列表
        List<UserRecord> userRecordList = iUserRecordService.findGroupByUserIdShare();
        return getUserVoList(userRecordList);
    }

    private List<UserVo> getUserVoList(List<UserRecord> userRecordList) {
        List<UserVo> dataList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(userRecordList)) {
            for (UserRecord item : userRecordList) {
                User user = iUserService.getUserById(item.getUserId());
                if (Objects.isNull(user)) {
                    continue;
                }
                UserVo userVo = UserVo.builder()
                        .userId(item.getUserId())
                        .userName(user.getNickname())
                        .mobile(user.getMobile())
                        .email(user.getEmail())
                        .openid(user.getOpenid())
                        .uploadRecordNum(iUserRecordService.getTotalByUserId(user.getId()))
                        .locked(user.getLocked())
                        .createTime(user.getCreatedAt())
                        .build();
                dataList.add(userVo);
            }
        }
        return dataList;
    }

    @Override
    @Transactional
    public Integer addRecord(RecordAddVo body) {

        log.info("------------------------------ 增加记录信息  ------------------------------");
        ApiResponseBody.printRequestParam(body);

        // 查询用户记录列表
        List<UserRecord> userRecordList = iUserRecordService.findByUserIdAndTitle(body.getUserId(),
                body.getRecordType());
        if (CollectionUtils.isEmpty(userRecordList)) {
            // 添加记录信息
            UserRecord userRecord = new UserRecord();
            userRecord.setUserId(body.getUserId());
            userRecord.setTitle(body.getRecordTitle());
            userRecord.setType(body.getRecordType());
            if (Objects.nonNull(body.getCreateTime())) {
                userRecord.setCreatedAt(body.getCreateTime());
            } else {
                userRecord.setCreatedAt(DateUtils.getSecondTimestamp());
            }
            userRecord.setWeight(body.getWeight());
            iUserRecordService.save(userRecord);

            // 批量添加记录详情
            batchAddRecordDetail(userRecord.getId(), body.getData());

            // 添加成功返回记录ID
            return userRecord.getId();
        }

        // 记录已存在时，返回0
        return 0;
    }

    @Transactional
    public void batchAddRecordDetail(Integer recordId, RoastDataVo data) {
        if (Objects.nonNull(data)) {
            final int now = DateUtils.getSecondTimestamp();
            int size = data.getTimeArray().size();
            List<UserRecordDetail> userRecordDetailList = Lists.newArrayList();
            for (int i = 0; i < size; i++) {
                UserRecordDetail userRecordDetail = new UserRecordDetail();
                userRecordDetail.setCreatedAt(now);
                userRecordDetail.setRecordId(recordId);
                userRecordDetail.setTNode(String.valueOf(data.getTimeArray().get(i)));
                userRecordDetail.setBtNode(getRecordValue(data.getBeanTemperatureArray(), i));
                userRecordDetail.setEtNode(getRecordValue(data.getEnvironmentTemperatureArray(), i));
                userRecordDetail.setFpNode(getRecordValue(data.getFirepowerArray(), i));
                userRecordDetail.setDpNode(getRecordValue(data.getDamperArray(), i));
                userRecordDetail.setMsNode(getRecordValue(data.getMotorSpeedArray(), i));
                userRecordDetail.setEvNode(0);
                for (RoastEvent item : data.getEventArray()) {
                    if (item.getTime().equals(data.getTimeArray().get(i))) {
                        userRecordDetail.setEvNode(item.getEvent());
                    }
                }
                userRecordDetailList.add(userRecordDetail);
            }
            iUserRecordDetailService.saveBatch(userRecordDetailList);
        }
    }

    /**
     * 获取记录值
     *
     * @param recordArray 记录信息
     * @param index       当前坐标
     * @return
     */
    private <T> String getRecordValue(ArrayList<T> recordArray, int index) {
        int size = recordArray.size();
        int maxIndex = size - 1;
        if (index >= size) {
            return String.valueOf(recordArray.get(maxIndex));
        } else if (index < 0) {
            return String.valueOf(recordArray.get(0));
        }
        return String.valueOf(recordArray.get(index));
    }

    @Override
    @Transactional
    public void updateUserRecord(RecordModVo body) {

        log.info("------------------------------ 更新用户曲线的title与type  ------------------------------");
        ApiResponseBody.printRequestParam(body);

        // 通过ID，查询用户记录信息
        UserRecord userRecord = iUserRecordService.getUserRecordById(body.getRecordId());
        if (Objects.isNull(userRecord)) {
            throw new CommonServiceException(ApiResponseCode.USER_RECORD_NOT_EXIST);
        }

        // 更新记录信息
        userRecord.setUpdatedAt(DateUtils.getSecondTimestamp());
        if (StringUtils.isNotBlank(body.getRecordTitle())) {
            userRecord.setTitle(body.getRecordTitle());
        }
        if (StringUtils.isNotBlank(body.getRecordType())) {
            userRecord.setType(body.getRecordType());
        }
        iUserRecordService.updateById(userRecord);
    }

    @Override
    @Transactional
    public void setIsSelect(RecordIdVo body) {

        log.info("------------------------------ 设置是否为精选曲线  ------------------------------");
        ApiResponseBody.printRequestParam(body);

        // 通过ID，查询用户记录信息
        UserRecord userRecord = iUserRecordService.getUserRecordById(body.getRecordId());
        if (Objects.isNull(userRecord)) {
            throw new CommonServiceException(ApiResponseCode.USER_RECORD_NOT_EXIST);
        }

        // 更新记录信息
        userRecord.setUpdatedAt(DateUtils.getSecondTimestamp());
        int selected = (Objects.nonNull(body.getSelected()) && Objects.equals(body.getSelected(), 1)) ? 1 : 0;
        userRecord.setSelected(selected);
        iUserRecordService.updateById(userRecord);
    }

    @Override
    @Transactional
    public void setIsTrain(RecordIdVo body) {

        log.info("------------------------------ 设置是否为训练集  ------------------------------");
        ApiResponseBody.printRequestParam(body);

        // 通过ID，查询用户记录信息
        UserRecord userRecord = iUserRecordService.getUserRecordById(body.getRecordId());
        if (Objects.isNull(userRecord)) {
            throw new CommonServiceException(ApiResponseCode.USER_RECORD_NOT_EXIST);
        }

        // 更新记录信息
        userRecord.setUpdatedAt(DateUtils.getSecondTimestamp());
        int train = (Objects.nonNull(body.getTrain()) && Objects.equals(body.getTrain(), 1)) ? 1 : 0;
        userRecord.setTrain(train);
        iUserRecordService.updateById(userRecord);
    }

    @Override
    @Transactional
    public void delTrainList(DelListBodyVo body) {

        log.info("------------------------------ 批量删除训练集  ------------------------------");
        ApiResponseBody.printRequestParam(body);

        if (CollectionUtils.isNotEmpty(body.getList())) {
            final int now = DateUtils.getSecondTimestamp();
            for (String id : body.getList()) {
                UserRecord userRecord = iUserRecordService.getUserRecordById(Integer.valueOf(id));
                if (Objects.nonNull(userRecord)) {
                    userRecord.setUpdatedAt(now);
                    userRecord.setTrain(0);
                    iUserRecordService.updateById(userRecord);
                }
            }
        }
    }

    @Override
    @Transactional
    public void setIsShare(RecordIdVo body) {

        log.info("------------------------------ 设置是否为分享  ------------------------------");
        ApiResponseBody.printRequestParam(body);

        // 通过ID，查询用户记录信息
        UserRecord userRecord = iUserRecordService.getUserRecordById(body.getRecordId());
        if (Objects.isNull(userRecord)) {
            throw new CommonServiceException(ApiResponseCode.USER_RECORD_NOT_EXIST);
        }

        // 更新记录信息
        userRecord.setUpdatedAt(DateUtils.getSecondTimestamp());
        int share = (Objects.nonNull(body.getShare()) && Objects.equals(body.getShare(), 1)) ? 1 : 0;
        userRecord.setShare(share);
        iUserRecordService.updateById(userRecord);
    }

    @Override
    @Transactional
    public void delRecord(DelBodyVo body) {

        log.info("------------------------------ 删除记录信息  ------------------------------");
        ApiResponseBody.printRequestParam(body);

        // 查询用户记录信息
        UserRecord userRecord = iUserRecordService.getUserRecordByIdAndUserId(body.getId(), body.getUserId());
        if (Objects.isNull(userRecord)) {
            throw new CommonServiceException(ApiResponseCode.USER_RECORD_NOT_EXIST);
        }

        // 逻辑删除用户记录信息
        userRecord.setDeletedAt(DateUtils.getSecondTimestamp());
        userRecord.setIsDelete(IsDeleteEnum.TYPE_1.toByte());
        iUserRecordService.updateById(userRecord);
    }

    @Override
    @Transactional
    public void delAllRecord(DelBodyVo body) {

        log.info("------------------------------ 删除所有记录信息  ------------------------------");
        ApiResponseBody.printRequestParam(body);

        List<UserRecord> userRecordList = iUserRecordService.findListByUserId(body.getUserId());
        if (CollectionUtils.isNotEmpty(userRecordList)) {
            userRecordList.forEach(item -> {
                item.setDeletedAt(DateUtils.getSecondTimestamp());
                item.setIsDelete(IsDeleteEnum.TYPE_1.toByte());
            });
            iUserRecordService.updateBatchById(userRecordList);
        }
    }

    @Override
    @Transactional
    public void delShare(DelBodyVo body) {

        log.info("------------------------------ 删除分享记录信息  ------------------------------");
        ApiResponseBody.printRequestParam(body);

        // 查询用户记录信息
        UserRecord userRecord = iUserRecordService.getUserRecordByIdAndUserId(body.getId(), body.getUserId());
        if (Objects.isNull(userRecord)) {
            throw new CommonServiceException(ApiResponseCode.USER_RECORD_NOT_EXIST);
        }

        // 取消分享曲线
        userRecord.setUpdatedAt(DateUtils.getSecondTimestamp());
        userRecord.setShare(0);
        iUserRecordService.updateById(userRecord);
    }

    @Override
    public void updateRecord(RecordUpdateVo body) {

        log.info("------------------------------ 更新记录信息  ------------------------------");
        ApiResponseBody.printRequestParam(body);

        // 验证用户记录是否存在
        UserRecord userRecord = iUserRecordService.getUserRecordById(body.getRecordId());
        if (Objects.isNull(userRecord)) {
            throw new CommonServiceException(ApiResponseCode.USER_RECORD_NOT_EXIST);
        }

        // 批量更新记录详情
        batchUpdateRecordDetail(userRecord.getId(), body.getData());
    }

    @Override
    public List<UserRecordVo> getRecordList(RecordListVo body) {
        List<UserRecord> userRecordList = iUserRecordService.findList(body.getUserId(),
                body.getSelected(), body.getShare(), body.getTrain());
        return getUserRecordVos(userRecordList);
    }

    @Override
    public List<BigDecimal> calcFirepower(CalcFirepowerVo body) {

        log.info("------------------------------ 计算火力  ------------------------------");
        ApiResponseBody.printRequestParam(body);

        List xTrain = Lists.newArrayList();
        List target = Lists.newArrayList();
        List xTest = Lists.newArrayList();

        // 训练集曲线列表
        List<UserRecord> trainRecordList = iUserRecordService.getTrainListByType(body.getType());
        if (CollectionUtils.isNotEmpty(trainRecordList)) {
            List xTrainList = null;
            List targetList = null;
            for (UserRecord item : trainRecordList) {
                List<UserRecordDetail> userRecordDetailList = iUserRecordDetailService.getUserRecordDetailList(item.getId());
                xTrainList = getXTrainDataList(userRecordDetailList);
                xTrain.addAll(xTrainList);
                targetList = getTargetDataList(userRecordDetailList);
                target.addAll(targetList);
            }
        }

        // 用户曲线列表
        List<UserRecord> userRecordList = iUserRecordService.getListByUserId(body.getUserId());
        if (CollectionUtils.isNotEmpty(userRecordList)) {
            List xTestList = null;
            for (UserRecord item : userRecordList) {
                List<UserRecordDetail> userRecordDetailList = iUserRecordDetailService.getUserRecordDetailList(item.getId());
                xTestList = getXTrainDataList(userRecordDetailList);
                xTest.addAll(xTestList);
            }
        }

        // 请求python接口，计算训练集取消
        String url = "http://39.103.170.204:8868/service";
        log.info("请求地址：{}", url);
        String resp = HttpUtil.doPost(url, String.valueOf(xTrain), String.valueOf(target), String.valueOf(xTest));
        log.info("响应结果：{}", resp);
        if (StringUtils.isNotEmpty(resp)) {
            List<BigDecimal> resultList = JSONObject.parseArray(resp, BigDecimal.class);
            return resultList;
        }
        return null;
    }

    @Override
    public void batchSetShare(RecordIdListVo body) {

        log.info("------------------------------ 批量设置分享  ------------------------------");
        ApiResponseBody.printRequestParam(body);

        if (Objects.nonNull(body.getRecordIdList())) {
            final int now = DateUtils.getSecondTimestamp();
            List<UserRecord> userRecordList = Lists.newArrayList();
            for (Integer recordId : body.getRecordIdList()) {
                UserRecord userRecord = iUserRecordService.getUserRecordById(recordId);
                if (Objects.nonNull(userRecord)) {
                    userRecord.setUpdatedAt(now);
                    userRecord.setShare(body.getShare());
                    userRecordList.add(userRecord);
                }
            }
            if (CollectionUtils.isNotEmpty(userRecordList)) {
                if (!iUserRecordService.updateBatchById(userRecordList)) {
                    throw new CommonServiceException(ApiResponseCode.BATCH_SETTING_FAILURE);
                }
            }
        }
    }

    @Override
    public void batchDelRecord(RecordIdListDelVo body) {

        log.info("------------------------------ 批量删除记录  ------------------------------");
        ApiResponseBody.printRequestParam(body);

        if (Objects.nonNull(body.getRecordIdList())) {
            final int now = DateUtils.getSecondTimestamp();
            List<UserRecord> userRecordList = Lists.newArrayList();
            for (Integer recordId : body.getRecordIdList()) {
                UserRecord userRecord = iUserRecordService.getUserRecordById(recordId);
                if (Objects.nonNull(userRecord)) {
                    userRecord.setDeletedAt(now);
                    userRecord.setIsDelete(IsDeleteEnum.TYPE_1.toByte());
                    userRecordList.add(userRecord);
                }
            }
            if (CollectionUtils.isNotEmpty(userRecordList)) {
                if (!iUserRecordService.updateBatchById(userRecordList)) {
                    throw new CommonServiceException(ApiResponseCode.BATCH_DEL_FAILURE);
                }
            }
        }
    }

    @Override
    public String getRecordToken(Integer recordId) {

        log.info("------------------------------ 获取曲线记录口令  ------------------------------");
        ApiResponseBody.printRequestParam(recordId);

        // 验证曲线记录是否存在
        UserRecord userRecord = iUserRecordService.getUserRecordById(recordId);
        if (Objects.isNull(userRecord)) {
            throw new CommonServiceException(ApiResponseCode.USER_RECORD_NOT_EXIST);
        }

        // 不存在生成口令
        if (StringUtils.isBlank(userRecord.getRecordToken())) {
            // 生成口令
            String recordToken = Generator.generateRecordToken();
            userRecord.setUpdatedAt(DateUtils.getSecondTimestamp());
            userRecord.setRecordToken(recordToken);
            iUserRecordService.updateById(userRecord);
        }

        return userRecord.getRecordToken();
    }

    @Override
    public UserRecordVo getRecordByRecordToken(String recordToken) {

        log.info("------------------------------ 根据口令，获取曲线记录  ------------------------------");
        ApiResponseBody.printRequestParam(recordToken);

        // 根据口令，查询曲线记录信息
        UserRecord userRecord = iUserRecordService.getUserRecordByRecordToken(recordToken);
        if (Objects.isNull(userRecord)) {
            throw new CommonServiceException(ApiResponseCode.USER_RECORD_NOT_EXIST);
        }

        UserRecordVo userRecordVo = UserRecordVo.builder()
                .recordId(userRecord.getId())
                .userId(userRecord.getUserId())
                .userName(iUserService.getNickNameByUserId(userRecord.getUserId()))
                .title(userRecord.getTitle())
                .type(userRecord.getType())
                .share(userRecord.getShare())
                .selected(userRecord.getSelected())
                .weight(userRecord.getWeight())
                .train(userRecord.getTrain())
                .isTop(userRecord.getIsTop())
                .createTime(userRecord.getCreatedAt())
                .build();
        return userRecordVo;
    }

    @Transactional
    @Override
    public void setIsTop(RecordIdVo body) {

        log.info("------------------------------ 设置是否置顶  ------------------------------");
        ApiResponseBody.printRequestParam(body);

        // 通过ID，查询用户记录信息
        UserRecord userRecord = iUserRecordService.getUserRecordById(body.getRecordId());
        if (Objects.isNull(userRecord)) {
            throw new CommonServiceException(ApiResponseCode.USER_RECORD_NOT_EXIST);
        }

        // 更新记录信息
        userRecord.setUpdatedAt(DateUtils.getSecondTimestamp());
        int isTop = (Objects.nonNull(body.getIsTop()) && Objects.equals(body.getIsTop(), 1)) ? 1 : 0;
        userRecord.setIsTop(isTop);
        iUserRecordService.updateById(userRecord);
    }

    @Transactional
    public void batchUpdateRecordDetail(Integer recordId, RoastDataVo data) {
        if (Objects.nonNull(data)) {
            final int now = DateUtils.getSecondTimestamp();
            int size = data.getTimeArray().size();
            List<UserRecordDetail> userRecordDetailList = Lists.newArrayList();
            for (int i = 0; i < size; i++) {
                UserRecordDetail userRecordDetail = iUserRecordDetailService.getUserRecordDetailByRecordIdAndTNode(recordId,
                        String.valueOf(data.getTimeArray().get(i)));
                if (Objects.isNull(userRecordDetail)) {
                    userRecordDetail = new UserRecordDetail();
                    userRecordDetail.setCreatedAt(now);
                    userRecordDetail.setRecordId(recordId);
                    userRecordDetail.setEvNode(0);
                } else {
                    userRecordDetail.setUpdatedAt(now);
                }
                userRecordDetail.setTNode(String.valueOf(data.getTimeArray().get(i)));
                userRecordDetail.setBtNode(String.valueOf(data.getBeanTemperatureArray().get(i)));
                userRecordDetail.setEtNode(String.valueOf(data.getEnvironmentTemperatureArray().get(i)));
                userRecordDetail.setFpNode(String.valueOf(data.getFirepowerArray().get(i)));
                userRecordDetail.setDpNode(String.valueOf(data.getDamperArray().get(i)));
                userRecordDetail.setMsNode(String.valueOf(data.getMotorSpeedArray().get(i)));
                for (RoastEvent item : data.getEventArray()) {
                    if (item.getTime().equals(data.getTimeArray().get(i))) {
                        userRecordDetail.setEvNode(item.getEvent());
                    }
                }
                userRecordDetailList.add(userRecordDetail);
            }
            iUserRecordDetailService.saveOrUpdateBatch(userRecordDetailList);
        }
    }

    private List getTargetDataList(List<UserRecordDetail> userRecordDetailList) {
        List resultList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(userRecordDetailList)) {
            for (UserRecordDetail item : userRecordDetailList) {
                resultList.add(item.getFpNode());
            }
        }
        return resultList;
    }

    private List getXTrainDataList(List<UserRecordDetail> userRecordDetailList) {
        List<List> resultList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(userRecordDetailList)) {
            List data = null;
            for (UserRecordDetail item : userRecordDetailList) {
                data = Lists.newArrayList();
                data.add(0, item.getTNode());
                data.add(1, item.getBtNode());
                data.add(2, item.getDpNode());
                resultList.add(data);
            }
        }
        return resultList;
    }

}
